﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LiJu
{
    public partial class AddUser : Form
    {

        /// <summary>
        /// ID
        /// </summary>
        public static int UId { get; set; }

        /// <summary>
        /// 用户ID
        /// </summary>
        public static string UserId { get; set; }

        /// <summary>
        /// 角色ID
        /// </summary>
        public static int RoleId { get; set; }

        /// <summary>
        /// 角色名称
        /// </summary>
        public static string RoleName { get; set; }

        /// <summary>
        /// 用户名称
        /// </summary>
        public static string UserName { get; set; }

        /// <summary>
        /// 用户密码
        /// </summary>
        public static string PassWord { get; set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public static bool State { get; set; }


        public AddUser()
        {
            InitializeComponent();

            //查询出所有角色
            string sql = "select Id,roleName from rolemanager where state=1";

            var roleList = UserOpMysql.ExecuteDataTable(sql); ;
            if (roleList.Rows.Count > 0)
            {
                this.RolecomboBox.DataSource = roleList;
                this.RolecomboBox.DisplayMember = "roleName";
                this.RolecomboBox.ValueMember = "Id";
            }
        }



        private void AddUser_Load(object sender, EventArgs e)
        {

            //修改
            if (UId > 0)
            {
                TbxUserNo.Text = UserId;

                if (UserId == "admin")
                {
                    TbxUserNo.Enabled = false;
                }
                TbxUserName.Text = UserName;
                TbxPwd.Text = EncryptionHelper.Decrypt(PassWord);
                RolecomboBox.SelectedValue = RoleId;
                RolecomboBox.Text = RoleName;
                CkbStatus.Checked = State;

            }

        }

        private void SaveUserInfoButton_Click(object sender, EventArgs e)
        {
            UserId = TbxUserNo.Text.Trim();
            UserName = TbxUserName.Text.Trim();
            PassWord = TbxPwd.Text.Trim();
            RoleId = Convert.ToInt32(RolecomboBox.SelectedValue);
            State = CkbStatus.Checked;


            if (string.IsNullOrWhiteSpace(UserId))
            {
                MessageBox.Show("用户编号不能为空！", "参数有误！", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            if (string.IsNullOrWhiteSpace(UserName))
            {
                MessageBox.Show("用户名称不能为空！", "参数有误！", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            if (string.IsNullOrWhiteSpace(PassWord) || PassWord.Length < 6)
            {
                MessageBox.Show("用户密码为空或者密码长度小于6位！", "参数有误！", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            if (RoleId == 0)
            {
                MessageBox.Show("用户角色不能为空！", "参数有误！", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }


            //存储过程名称
            string sql = "InsertAndUpdateUserManager";

            List<MySqlParameter> mySqlParameters = new List<MySqlParameter>()
            {
                new MySqlParameter("?p_userId",MySqlDbType.VarChar){Value=UserId},
                new MySqlParameter("?p_userName",MySqlDbType.VarChar){Value=UserName},
                new MySqlParameter("?p_passWord",MySqlDbType.VarChar){Value=EncryptionHelper.Encrypt(TbxPwd.Text.Trim())},
                new MySqlParameter("?p_userRole",MySqlDbType.Int32){Value=RoleId},
                new MySqlParameter("?p_state",MySqlDbType.Int32){Value=State},
                new MySqlParameter("?p_opid",MySqlDbType.Int32){Value=UId}

            };

            var result = UserOpMysql.ExecuteStoredProcedureToDataTable(sql, mySqlParameters);
            if (result.Rows.Count > 0)
            {
                string msg = Convert.ToString(result.Rows[0]["message"]);


                MessageBox.Show(msg, "处理信息！", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                PageDataDto.SystemLogInfoAdd("用户管理", msg);

                return;

            }
        }

        private void Cancelbutton_Click(object sender, EventArgs e)
        {
            this.Close();

        }

        private void AddUser_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void TbxUserNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar >= '0' && e.KeyChar <= '9' || Char.IsLetter(e.KeyChar))//输入1-12位数字或字母
            {
                if (TbxUserNo.Text.Length <= 11)
                {
                    e.Handled = false;
                }
                else if (TbxUserNo.SelectionLength > 1)
                {
                    e.Handled = false;//选择多个
                }
                else
                {
                    e.Handled = true;
                }
            }

            //e.KeyChar == '.' ||
            else if (e.KeyChar == (char)Keys.Return) //Tab或回车键
            {
                e.Handled = true;
                SendKeys.Send("{TAB}");
            }
            else if (e.KeyChar == '\b' || (int)e.KeyChar == 7)
                e.Handled = false;//删除
            else
                e.Handled = true;
        }

        private void TbxPwd_KeyPress(object sender, KeyPressEventArgs e)
        {

            //string regx = @"(?=.*[a-z])(?=.*\\d)(?=.*[#@!~%^&*])[a-z\\d#@!~%^&*]{6,16}";



            if (e.KeyChar >= '0' && e.KeyChar <= '9' || Char.IsLetter(e.KeyChar) || Char.IsPunctuation(e.KeyChar))//输入1-16位数字或字母
            {
                if (TbxPwd.Text.Length <= 15)
                {
                    e.Handled = false;
                }
                else if (TbxPwd.SelectionLength > 1)
                {
                    e.Handled = false;//选择多个
                }
                else
                {
                    e.Handled = true;
                }
            }
            else if (e.KeyChar == (char)Keys.Return) //Tab或回车键
            {
                e.Handled = true;
                SendKeys.Send("{TAB}");
            }
            else if (e.KeyChar == '\b' || (int)e.KeyChar == 7)
                e.Handled = false;//删除
            else
                e.Handled = true;
        }

        private void TbxUserName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar >= '0' && e.KeyChar <= '9' || Char.IsLetter(e.KeyChar))//输入1-8位数字或字母
            {
                if (TbxUserName.Text.Length <= 7)
                {
                    e.Handled = false;
                }
                else if (TbxUserName.SelectionLength > 1)
                {
                    e.Handled = false;//选择多个
                }
                else
                {
                    e.Handled = true;
                }
            }

            //e.KeyChar == '.' ||
            else if (e.KeyChar == (char)Keys.Return) //Tab或回车键
            {
                e.Handled = true;
                SendKeys.Send("{TAB}");
            }
            else if (e.KeyChar == '\b' || (int)e.KeyChar == 7)
                e.Handled = false;//删除
            else
                e.Handled = true;
        }


        private void TbxUserNo_Leave(object sender, EventArgs e)
        {

            ////匹配天数，最多365天，最小1天
            //string pattern = @"^(1[0-9]{2}|[1-9][0-9]?|36[0-5]|[1-9])$";

            //TextBoxIsMatchData(pattern, TbxUserNo, "输入的内容不符合规则，请重新输入！最小1天，最大365天", UserId);
        }

        private void TbxUserName_Leave(object sender, EventArgs e)
        {

            ////匹配天数，最多365天，最小1天
            //string pattern = @"^(1[0-9]{2}|[1-9][0-9]?|36[0-5]|[1-9])$";

            //TextBoxIsMatchData(pattern, TbxUserName, "输入的内容不符合规则，请重新输入！最小1天，最大365天", UserName);
        }

        private void TbxPwd_Leave(object sender, EventArgs e)
        {

            ////密码长度至少为6位，且包含大小写字母、数字至少各一位
            //string pattern = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,16}$";

            //TextBoxIsMatchData(pattern, TbxPwd, "输入的内容不符合规则，请重新输入！密码长度至少为6位，且包含大小写字母、数字至少各一位", PassWord);
        }

        /// <summary>
        /// 校验输入的内容是否符合规则
        /// </summary>
        /// <param name="pattern">正则表达式</param>
        /// <param name="textBox">文本框</param>
        /// <param name="errMsg">消息提示</param>
        public void TextBoxIsMatchData(string pattern, TextBox textBox, string errMsg, string oldValue = "")
        {

            //获取单元格的输入值
            string inputValue = textBox.Text;

            // 创建Regex对象并进行匹配测试
            Regex regex = new Regex(pattern);
            if (!regex.IsMatch(inputValue))
            {


                MessageBox.Show(errMsg, "异常提示！");

                // 设置焦点
                textBox.Text = oldValue;
                textBox.Focus();
                return;

            }
        }

        
    }
}
